/* eslint-disable default-case */
/* eslint-disable array-callback-return */
/* eslint-disable consistent-return */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  getEmpNameList,
  getDeduAssDetail,
  getAssUpdateDetail,
  getAcountList,
  getSecAccoList,
  addSubmit,
  updateSubmit,
  getDownloadInfo,
  getUploadProgress,
  uploadFileAddAss,
} from '@/services/addass';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'addass';
const ModelAddEmp = {
  namespace,
  state: {
    empNameList: [], // 单个调整雇员姓名
    // 增加险种前查看
    assList: [], // 已有社保信息
    basicInsInfo: { grpId: '', custId: null }, // 基本信息
    tableId: 1,
    assVoList: [
      {
        id: 0,
        assList: [],
        payWay: undefined, // 缴费方式
        payWayList: [],
        accoId: undefined, // 缴费账户
        accountList: [], // 缴费账户列表
        injSecAccoId: undefined, // 工伤二级户
        isHasInj: false, // 有无工伤险
        secAccuList: [], // 工伤二级户列表
        startYm: undefined,
        isSupplyRun: false, // 是否是供应商执行
        kinds: undefined, //  选中的险种
      },
    ],
    sendId: null,
    batchQuery: {
      progressPercent: 0,
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/addTask/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    // 单个调整：输入姓名,证件号模糊查询
    *fetchEmpNameList({ payload }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        yield put({
          type: 'getEmpNameList',
          payload: response.data,
        });
        return response.data;
      }
      message.warning(response.message || '获取员工信息：服务端错误');
    },
    // 查询已有社保险种列表:查询信息
    *fetchAssDetail({ payload }, { call, put, select }) {
      let assVoList = yield select(state => state.addass.assVoList);
      const response = yield call(
        payload.addTaskId ? getAssUpdateDetail : getDeduAssDetail,
        payload
      );
      if (response.success) {
        if (
          response.data.basicInsInfo &&
          response.data.basicInsInfo.payWayList &&
          response.data.basicInsInfo.payWayList.length
        ) {
          assVoList = assVoList.map(item => ({
            ...item,
            payWayList: response.data.basicInsInfo.payWayList,
            isSupplyRun: response.data.basicInsInfo.execType === 2 || false,
            assList: response.data.basicInsInfo.assList,
          }));
        }
        if (payload.addTaskId) {
          // 修改处理表格数据
          assVoList = [];
          if (response.data.assList && response.data.assList.length) {
            assVoList = response.data.assList.map((item, index) => ({
              ...item,
              id: `${item.startYm}-${index}`,
              assList: response.data.basicInsInfo.assList || [],
              kinds: item.assList,
              payWayList: response.data.basicInsInfo.payWayList || [],
              accountList: [],
              payWay: `${item.payWay}`,
              isHasInj: item.assList.indexOf(5) > -1, //  是否有工伤险
              injSecAccoId: (item.injSecAccoId && [item.injAccoId, item.injSecAccoId]) || undefined,
              isSupplyRun: response.data.basicInsInfo.execType === 2 || false,
            }));
          }
        }
        yield put({
          type: 'updateModelData',
          payload: {
            ...payload,
            ...response.data,
            assVoList,
            areaId: (response.data.basicInsInfo && response.data.basicInsInfo.areaId) || null,
            sendId: (response.data.basicInsInfo && response.data.basicInsInfo.sendId) || null,
          },
        });
      }
      return response;
    },

    // 获取缴费账户列表
    *fetchAcountList(
      {
        payload: { custId, areaId, insKinds, payWay, id },
      },
      { call, put, select }
    ) {
      const basicInsInfo = yield select(state => state.addass.basicInsInfo);
      const response = yield call(getAcountList, {
        custId,
        areaId,
        insKinds,
        payWay,
        grpId: basicInsInfo.grpId,
      });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              accountList: response.data,
            },
          });
          yield put({
            type: 'updateTableData',
            payload: { targetKey: 'accountList', value: response.data, id },
          });
        } else {
          message.warning('该地区下该险种未维护缴费账户');
        }
      } else {
        message.warning(response.message || '获取缴费账户列表：服务端错误');
      }
    },
    // 获取工伤二级户列表
    *fetchSecAccoList(
      {
        payload: { custId, areaId, insKinds, payWay, id },
      },
      { call, put, select }
    ) {
      const basicInsInfo = yield select(state => state.addass.basicInsInfo);
      const response = yield call(getSecAccoList, {
        custId,
        areaId,
        insKinds,
        payWay,
        grpId: basicInsInfo.grpId,
      });
      if (response.success) {
        if (response.data) {
          response.data.map(item => {
            const temp = item;
            temp.value = item.accoId;
            temp.label = item.accoName;
            temp.isLeaf = (item.injSecAccoDtos && false) || true;
            if (item.injSecAccoDtos) {
              const children = [];
              item.injSecAccoDtos.map(c => {
                children.push({
                  value: c.injSecAccoId,
                  label: c.injSecAccoName,
                  isLeaf: true,
                });
              });
              temp.children = children;
            }
          });
          const secAccuList = response.data;
          let secAccuIntValue;
          if (
            secAccuList.length === 1 &&
            secAccuList[0].injSecAccoDtos &&
            secAccuList[0].injSecAccoDtos.length === 1
          ) {
            secAccuIntValue = [
              secAccuList[0].accoId,
              secAccuList[0].injSecAccoDtos[0].injSecAccoId,
            ];
            yield put({
              type: 'updateTableData',
              payload: { targetKey: 'injSecAccoId', value: secAccuIntValue, id },
            });
          }
          yield put({
            type: 'updateModelData',
            payload: {
              secAccuList,
            },
          });
          yield put({
            type: 'updateTableData',
            payload: { targetKey: 'secAccuList', value: response.data, id },
          });
        } else {
          message.warning('该地区下未维护社工伤二级户');
        }
      } else {
        message.warning(response.message || '获取工伤二级户列表：服务端错误');
      }
    },
    // 提交数据
    submit:[
      function* ({ payload }, { call, put, select }) {
        const assInfo = yield select(state => state.addass);
        const { sendId } = assInfo;
        let submitData = (sendId && { sendId, ...payload.values }) || payload.values;
        submitData = payload.addTaskId ? { ...submitData, addTaskId: payload.addTaskId } : submitData;
        const response = yield call(payload.addTaskId ? updateSubmit : addSubmit, submitData);
        if (response.success) {
          message.success(payload.addTaskId ? '保存成功!' : '新增成功！');
          yield put(
            routerRedux.push({
              pathname: payload.addTaskId
                ? '/customservicemanage/addemployee/index'
                : '/customservicemanage/addemployee/addassfinish',
            })
          );
        } else {
          message.warning(`${response.message || '保存失败！'}`);
        }
      },
      { type:'throttle',ms:10000 }
    ],
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },

    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFileAddAss, payload);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 }
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.addass);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 单个调整：雇员姓名
    getEmpNameList(state, { payload }) {
      return {
        ...state,
        empNameList: payload,
      };
    },
    // 更新地区下表格数据源
    updateTableData(
      state,
      {
        payload: { targetKey, value, id },
      }
    ) {
      const { assVoList } = state;
      assVoList.map((item, index) => {
        if (item.id === id) {
          assVoList[index][targetKey] = value;
        }
        return true;
      });
      return {
        ...state,
        ...assVoList,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
}

export default ModelAddEmp;

